import { lstatSync, readdirSync, readFileSync } from 'fs'
import { I18N_LOADER_OPTIONS, I18nAbstractLoader, I18nAbstractLoaderOptions, I18nTranslation } from 'nestjs-i18n'
import * as path from 'path'
import { Inject } from '@nestjs/common'

export class I18nFileJsonLoader extends I18nAbstractLoader {
  constructor(
    @Inject(I18N_LOADER_OPTIONS)
    private option: I18nAbstractLoaderOptions
  ) {
    super(option)
  }

  formatData(data: any) {
    return JSON.parse(data)
  }

  getDefaultOptions(): Partial<I18nAbstractLoaderOptions> {
    return {
      filePattern: '*.json',
      watch: false,
    }
  }

  /**
   * 只读取path下的一级文件为语言包
   *
   * @returns
   */
  parseLanguagesSync(): string[] {
    const i18nPath = path.normalize(this.option.path + path.sep)
    const files = readdirSync(i18nPath)
    return files
      .filter(file => lstatSync(path.join(i18nPath, file)).isFile())
      .map(file => file.slice(0, -path.extname(file).length))
  }

  /**
   * 只读取path下的一级json文件作为语言包
   *
   * @returns
   */
  parseTranslationsSync(): I18nTranslation {
    const translations: I18nTranslation = {}
    const i18nPath = path.normalize(this.option.path + path.sep)
    const languages = this.parseLanguagesSync()

    for (const lang of languages) {
      const data = this.formatData(readFileSync(path.join(i18nPath, lang + '.json')))
      translations[lang] = data ?? {}
    }

    return translations
  }

  protected parseLanguages(): Promise<string[]> {
    return Promise.resolve(this.parseLanguagesSync())
  }

  protected parseTranslations(): Promise<I18nTranslation> {
    return Promise.resolve(this.parseTranslationsSync())
  }
}
